package cn.tedu.eguser1.controller;

import cn.tedu.eguser1.base.response.JsonResult;
import cn.tedu.eguser1.mapper.UserMapper;
import cn.tedu.eguser1.pojp.dto.UserAddParam;
import cn.tedu.eguser1.pojp.dto.UserUpdateParam;
import cn.tedu.eguser1.pojp.entity.User;
import cn.tedu.eguser1.pojp.vo.UserListVO;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Validated
@RestController
@RequestMapping("v1/user/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("add")
    public JsonResult addUser(@Validated @RequestBody  UserAddParam userAddParam) {
        System.out.println("用户添加：" + userAddParam);
        User user = new User();
        BeanUtils.copyProperties(userAddParam, user);

        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());

        System.out.println("用户对象：" + user);
        userMapper.insertUser(user);

        return JsonResult.ok();
    }

    @GetMapping("list")
    public JsonResult selectUser() {
        System.out.println("查询所有用户");
        List<UserListVO> userListVOS = userMapper.selectUser();
        return JsonResult.ok(userListVOS);
    }

    @PostMapping("del")
    public JsonResult deleteUser(@Range(min = 1, max = 100, message = "编号在1~100之间") Long id) {
        System.out.println("删除用户：" + id);
        userMapper.deleteUser(id);
        System.out.println("用户删除成功！");
        return JsonResult.ok();
    }

    @PostMapping("update")
    public JsonResult updateUser(@RequestBody UserUpdateParam userUpdateParam) {
        System.out.println("修改用户：" + userUpdateParam);
        User user = new User();
        BeanUtils.copyProperties(userUpdateParam, user);

        user.setUpdateTime(new Date());

        userMapper.updateUser(user);
        System.out.println("修改用户成功！");
        return JsonResult.ok();
    }

}
